<template>
  <div class="index-container" v-bind:style="{ minHeight: `calc(100vh - ${navBarHeight}px)` }">
    <van-nav-bar :title="titleName + '丨选手投票'" left-arrow @click-left="onClickLeft" ref="nav" />
    <div class="warpper" v-bind:style="{ marginTop: `${navBarHeight}px` }" ref="container">
      <van-loading size="40px" v-if="isloadig === false">加载中...</van-loading>
      <div class="" v-else>
        <!-- banner -->
        <van-swipe :autoplay="3000" style="transform:translate3d(0,0,0);overflow:hidden;">
          <van-swipe-item v-for="(image, index) in banner" :key="index">
            <img :src="image" style="height: 100%;width: 100%;transform:translate3d(0,0,0)" />
          </van-swipe-item>
        </van-swipe>
        <!-- 倒计时 -->
        <div class="race-countdown">
          <div class="entries_name">招商银行“出彩招行人”才艺大赛</div>
          <div class="flip-down" v-if="competitonInfo.status == 1">
            <div class="tip-entries_name">投票截止倒计时</div>
            <flip-countdown :deadline="finishTime" class="flip-dwon"></flip-countdown>
          </div>
          <div class="vote-end" v-if="competitonInfo.status == -1">投票已截止</div>
          <div class="vote-end" v-if="competitonInfo.status == 0">投票未开始</div>
          <div class="text-tip">
            <span>投票时间：{{ competitonInfo.start_time }} — {{ competitonInfo.end_time }}</span>
            <span>投票规则：{{ competitonInfo.vote_rule }}</span>
          </div>
        </div>
        <!-- 搜索列表 -->
        <div class="search-list">
          <!-- 搜索框 -->
          <div class="search">
            <div class="search-box">
              <div class="search-flex">
                <div class="search-img"><img src="../../assets/img/searchImg.png" /></div>
                <input type="text" placeholder="作品名称/作品编号/选手名称" v-model="search" />
              </div>
              <div class="search-btn" @click="goSearch">搜索</div>
            </div>
          </div>
          <!-- 列表 -->
          <div class="list-box">
            <div class="bg" :class="isFixed == true ? 'fixed' : ''">
              <div class="flex">
                <div class="search-entries_name boder" @click="showScreen(1)">
                  {{ bankName == '' || bankName == '全部' ? '单位选择' : bankName }}
                  <img src="../../assets/img/xiala.png" class="img-icon" />
                </div>
                <div class="search-entries_name" @click="showScreen(2)">
                  {{ cateName == '' || cateName == '全部' ? '才艺类型' : cateName }}
                  <img src="../../assets/img/xiala.png" class="img-icon" />
                </div>
              </div>
            </div>
            <div class="list-box2">
              <div class="class-item">
                <div class="flex">
                  <div class="item" @click="goScreen(1)" :class="type == 1 ? 'bg-hu' : ''">按热度排序</div>
                  <div class="item" @click="goScreen(2)" :class="type == 2 ? 'bg-hu' : ''">按编号排序</div>
                </div>
                <div class="hot-dec item" @click="setOrderType">
                  <span>排序方式</span>
                  <img src="../../assets/img/honr.png" alt="" class="img" v-if="orderType == 0" />
                  <img src="../../assets/img/down.png" alt="" class="img" v-if="orderType == 1" />
                  <img src="../../assets/img/up.png" alt="" class="img" v-if="orderType == 2" />
                </div>
              </div>
              <div class="list-info" v-if="list.length > 0">
                <van-list v-model="loading" :finished="finished" finished-text="没有更多了" :immediate-check="false"
                  @load="onRefresh()">
                  <div style="display: flex; justify-content: space-between; flex-wrap: wrap">
                    <div class="item" v-for="(item, index) in list" :key="index">
                      <router-link class="img"
                        :to="{ path: '/vote/detailCompetition', query: { id: item.id, name: item.entries_name } }">
                        <img :src="item.image" alt="" />
                        <div class="label">{{ item.rank_num }}</div>
                      </router-link>
                      <router-link class="cont-info"
                        :to="{ path: '/vote/detailCompetition', query: { id: item.id, name: item.entries_name } }">
                        <div class="cont line1 font-w">
                          <span class="span line1">{{ item.zeroId }} <span class="name">{{ item.name }}</span></span>
                          <span class="sapn1 line1">《{{ item.entries_name }}》</span>
                        </div>
                        <div class="addres">
                          <img src="../../assets/img/资源33.png" alt="" /><span class="line1"> {{ item.bank.name }}<sapn
                              v-if="item.department_name">-</sapn>{{ item.department_name }}</span>
                        </div>
                        <div class="vote font-w">{{ item.vote_num }}票</div>
                      </router-link>
                      <div class="button">
                        <div class="vote-btn" @click="goVote(item)" v-if="competitonInfo.status == 1">
                          {{ item.is_enable_vote == 1 ? '投票' : '今日已投票' }}</div>
                        <div class="vote-btn on" v-if="competitonInfo.status == 0"> 投票未开始</div>
                        <div class="vote-btn on" v-if="competitonInfo.status == -1"> 投票已截止</div>
                      </div>
                    </div>
                  </div>
                </van-list>
              </div>
              <noData :show="showNodata" v-else></noData>
            </div>
          </div>
        </div>
        <van-popup v-model="show">
          <div class="search-popup">
            <div class="title">
              <div class="span1" v-if="isType == 1">恭喜！</div>
              <div class="span1" v-if="isType == 2">抱歉....</div>
              <div class="" v-if="isType == 3">
                <div class="span pt33">抱歉，没有找到哦</div>
                <div class="pb30">请确认信息正确</div>
              </div>
              <div class="" v-if="isType == 1">
                投票成功！
                <div class="mt5">谢谢您的支持</div>
              </div>
              <!-- 不能投 -->
              <div class="" v-if="isType == 2">
                您今日已投过该作品
                <div class="mt5">看看别的吧</div>
              </div>
            </div>
            <div class="img">
              <!-- 没找到 -->
              <img src="../../assets/img/vote/noIcon.png" alt="" v-if="isType == 3" />
              <!-- 恭喜 -->
              <img src="../../assets/img/vote/happyIcon.png" alt="" v-if="isType == 1" />
              <!-- 不能投 -->
              <img src="../../assets/img/vote/sorryIcon.png" alt="" v-if="isType == 2" />
            </div>
            <div class="confirm" @click="hiddenShow">确定</div>
          </div>
        </van-popup>
        <van-popup v-model="screentrue" position="bottom" class="noPopup">
          <van-picker :entries_name="entries_name" show-toolbar value-key="name" :columns="screenList"
            @confirm="onConfirm" @cancel="onCancel" @change="onChange" />
        </van-popup>
      </div>
    </div>
  </div>
</template>

<script>
import { getCompetitonDetails, getCompetitonBank, getCompetitonKind, getCompetitonPlayer, Vote } from '@/api/user.js'
import FlipCountdown from 'vue2-flip-countdown'
import noData from '@/components/noData'
import { fillNumber } from '../../utils/index'
// getBase64Image
import { mapGetters } from 'vuex'
import debounce from 'lodash.debounce' // 防抖插件
// import MobileJS from '@/utils/MobileJS-1.0.6'
// console.log(MobileJS.camera(),'MobileJS')
// import MobileJS from '@/utils/MobileJS-1.0.6'
const NAME = 'Competition'
export default {
  name: NAME,
  components: {
    FlipCountdown,
    noData
  },
  data() {
    return {
      finishTime: '',
      navBarHeight: 0,
      isFixed: false, // 是否固定
      screentrue: false, // 下拉菜单控制显示隐藏
      show: false, // 弹窗显示隐藏
      images: [],
      entries_name: '', // 下拉菜单选择
      type: 1, // 编号样式控制
      orderType: 0, // 0代表原本，1代表升序，2代表降序
      branch: [], // 银行
      talentType: [], // 才艺
      screenList: [], // 银行&才艺
      searchList: [],
      isType: 0,
      pid: '',
      page: 1, // 页码
      num: 15, // 分页数量
      list: [], // 数据
      refreshing: false,
      finished: false,
      pagesize: 4,
      sort_key: 'vote_num', // 编号（employee_number修改=>id）,热度（vote_num）
      sort_val: '', // 升序（asc）,降序（desc）
      category_id: '', // 分类
      bank_id: '', // 银行,
      showPopIndex: 0,
      loadTitle: '',
      loading: false,
      loadend: false,
      competitonInfo: {},
      banner: [],
      listIndex: '',
      search: '', // 搜索文字
      cateName: '',
      bankName: '',
      titleName: '赛区',
      isloadig: false
    }
  },
  computed: {
    ...mapGetters(['tabBarHeight']),
    showNodata() {
      return this.searchList.length === 0
    }
  },
  mounted() {
    this.navBarHeight = this.$refs.nav.$el.offsetHeight
    window.addEventListener('scroll', this.handleScroll)
    this.getDetails()
    this.getKind()
    this.getBank()
  },
  created() {
    this.pid = this.$route.query.id
    this.onRefresh()
  },
  beforeRouteLeave(to, form, next) {
    window.removeEventListener('scroll', this.handleScroll)
    next()
  },
  methods: {
    request() {
      const params = {
        competition_id: this.pid,
        sort_key: this.sort_key,
        sort_val: this.sort_val,
        category_id: this.category_id,
        bank_id: this.bank_id,
        search: this.search,
        page: this.page,
        pagesize: this.num
      }
      getCompetitonPlayer(params).then(res => {
        this.isloadig = true
        if (res.data) {
          this.onLoad(
            res.data.map(item => {
              let numLen = item.id.toString().length
              item.zeroId = fillNumber(numLen, item.id)
              return item
            })
          )
        }
        if (res.code === 2002 || res.code === 2003) {
          if (this.search !== '' && this.list.length === 0) {
            this.isType = 3
            this.show = !this.show
          }
        }
      })
    },
    onLoad(data) {
      if (this.refreshing) {
        this.list = []
        this.refreshing = false
        this.page = 1
      }
      this.list.push(...data)
      this.loading = false
      this.page = this.page + 1
      if (data.length <= 0 || data.length < this.num) {
        this.finished = true
      }
    },
    onRefresh() {
      // // 清空列表数据
      this.finished = false
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      // 重新加载数据
      this.request()
    },
    // 获取赛区详情
    getDetails() {
      const that = this
      const param = {
        id: that.pid
      }
      getCompetitonDetails(param)
        .then(res => {
          if (res.code === 200) {
            const datas = res.data
            that.competitonInfo = datas
            that.banner = datas.banner.split('|')
            that.finishTime = datas.end_time
            this.titleName = datas.name
          }
        })
        .catch(() => { })
    },
    // 获取银行分类getCompetitonBank
    getBank() {
      const that = this
      const param = {
        id: that.pid
      }
      getCompetitonBank(param)
        .then(res => {
          if (res.code === 200) {
            const datas = res.data
            that.branch = datas
            that.branch.unshift({
              name: '全部'
            })
          }
        })
        .catch(() => { })
    },
    // 获取才艺分类getCompetitonKind
    getKind() {
      const that = this
      getCompetitonKind()
        .then(res => {
          if (res.code === 200) {
            const datas = res.data
            that.talentType = datas
            that.talentType.unshift({
              name: '全部'
            })
          }
        })
    },

    goVote: debounce(function (item) {
      
      if (item.is_enable_vote === 0) {
        this.isType = 2
        this.show = !this.show
        return
      }
      const param = {
        id: item.id
      }
      Vote(param).then(res => {
        if (res.code === 200) {
          // 投票成功
          this.isType = 1
          this.show = !this.show
          item.vote_num++
          item.is_enable_vote = 0
        } else if (res.code === 2000) {
          if (res.status !== -1) {
            this.isType = 2
            this.show = !this.show
          }
        } else {
          this.$toast(res.msg)
        }
      })
    }, 300),

    // 顶部固定
    handleScroll() {
      // 改变元素#searchBar的top值
      var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop // 滚动条距离顶部的距离
      if (document.querySelector('.list-box')) {
        var offsetTop = document.querySelector('.list-box').offsetTop // 4116 元素距离顶部的距离
        if (scrollTop >= offsetTop) {
          this.isFixed = true
        } else {
          this.isFixed = false
        }
      }
    },

    // 热度筛选
    goScreen(e) {
      this.type = e
      // 编号（employee_number）,热度（vote_num）
      if (this.type === 1) {
        this.sort_key = 'vote_num'
      } else {
        this.sort_key = 'id'
      }
      this.page = 1
      this.list = []
      this.onRefresh()
    },
    onClickLeft() {
      this.$router.go(-1)
    },
    // 搜索选手防抖
    goSearch: debounce(function (e) {
      // this.search = this.$refs.getValue.value
      // if (this.search === '') return
      this.page = 1
      this.list = []
      this.onRefresh()
    }, 300),
    hiddenShow() {
      this.show = false
      console.log(this.isType, 'ppthis.isType')
      if (this.isType === 3) {
        this.search = ''
        this.page = 1
        this.list = []
        this.onRefresh()
      }
    },
    // 分类筛选
    showScreen(e) {
      if (e === 1) {
        this.screenList = this.branch
        this.entries_name = '单位选择'
        this.showPopIndex = e
      } else {
        this.screenList = this.talentType
        this.entries_name = '才艺类型'
        this.showPopIndex = e
      }
      this.screentrue = !this.screentrue
    },
    onConfirm(value, index) {
      if (this.showPopIndex === 1) {
        this.bank_id = this.screenList[index].id
        this.bankName = value.name
      } else {
        this.category_id = this.screenList[index].id
        this.cateName = value.name
      }
      this.screentrue = !this.screentrue
      this.page = 1
      this.list = []
      this.onRefresh()
    },
    onChange(picker, value, index) { },
    // 取消选择
    onCancel() {
      this.screentrue = false
    },
    setOrderType: debounce(function (e) {
      const orderType = this.orderType
      // 升序（asc）,降序（desc）
      if (orderType === 0) {
        this.orderType = 1
        this.sort_val = 'asc'
      } else if (orderType === 1) {
        this.orderType = 2
        this.sort_val = 'desc'
      } else if ((orderType === 2)) {
        this.orderType = 0
        this.sort_val = ''
      }
      this.page = 1
      this.list = []
      this.onRefresh()
    }, 300)
  }
}
</script>

<style lang='scss' scoped>
@import './css/competition.scss';
.font-w{
  font-weight: 600;
}
.name{
  font-size: 16px !important;
}

:deep(.flip-card__top){
  background: linear-gradient(360deg, #FEFEFE 0%, #E6E5E8 100%) !important;
  color: #F94B73 !important;
}
:deep(.flip-card__bottom){
  background: linear-gradient(360deg, #FEFEFE 0%, #E6E5E8 100%) !important;
  color: #F94B73 !important;
  border-top: solid 1px #7F7E7E !important;
}
:deep(.flip-card__back-bottom){
  background: linear-gradient(360deg, #FEFEFE 0%, #E6E5E8 100%) !important;
  color: #F94B73 !important;
}

:deep(.flip-card__back)::before{
  background: linear-gradient(360deg, #FEFEFE 0%, #E6E5E8 100%) !important;
  color: #F94B73 !important;
}
:deep(.flip-card__back-bottom)::after{
  background: linear-gradient(360deg, #FEFEFE 0%, #E6E5E8 100%) !important;
  color: #F94B73 !important;
}

.list-box2 .nodata {
  position: static;
  width: 100%;
  height: auto;
  transform: translate(0);
  z-index: 10;
  display: flex;
  align-content: center;
  flex-wrap: wrap;
  flex-direction: column;
}

/deep/ .nodata .nodata_img {
  width: 100px;
  height: 100px;
  margin-top: 20px;
  margin-bottom: 20px;
}

/deep/ .van-popup {
  border-radius: 6px 6px 0 0 !important;
}

/deep/ .van-picker__confirm {
  color: #F61E51 !important;
}
</style>
